import './modules/echarts.js'
import './modules/dataTool.js'
import * as chart_data from './chart_data.js'

function set_chart(data, type_name)
{
    data = data["data"];
    var formate_data = chart_data.formate_data(data, type_name);
    var option = chart_data.get_option(formate_data, type_name);
    myChart.setOption(option);
}

function onSubmitClick() {
//    var x =
    var select_devices = document.getElementById("select_device");
    var select_type = document.getElementById("select_type");
    var device_id = select_devices.options[select_devices.selectedIndex].value;
    var type_name = select_type.options[select_type.selectedIndex].value;

//    console.log("device_id:", device_id);
//    console.log("type_name:", type_name);
    var data = {
        "device_id": device_id,
        "type_name": type_name,
    };
    fetch("/api/get_latency_data", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
    }).then(function(response) {
        return response.json();
    }).then(function(data) {
        set_chart(data, type_name);
    }).catch(function(error) {
        console.error("Error:", error);
    });
}

function set_selection()
{
    fetch("/api/get_device_test_list", {
        method: "Get",
        headers: {
            "Content-Type": "application/json"
        },
    }).then(function(response) {
        return response.json();
    }).then(function(data) {
        set_device_list(data["device_list"]);
        set_test_list(data["test_list"]);
    }).catch(function(error) {
        console.error("Error:", error);
    });
}

function set_device_list(devices)
{
//    console.log("devices:", JSON.stringify(devices));
    var select_devices = document.getElementById("select_device");
    select_devices.options.length = 0;
//    select_devices.add(new Option("全部", "all"));
    for(var i = 0; i < devices.length; i++)
    {
        var id = devices[i]["DeviceID"];
        var str = devices[i]["Vendor"] + "-" +
            devices[i]["DeviceModel"] + "-" +
            devices[i]["OSInfo"] + "-" +
            id.substring(id.length - 4, id.length);
        select_devices.add(new Option(str, id));
    }
}

function set_test_list(type_name)
{
    var select_type = document.getElementById("select_type");
    select_type.options.length = 0;
//    select_type.add(new Option("全部", "all"));
    for(var i = 0; i < type_name.length; i++)
    {
        var str = type_name[i]["type_name"];
        select_type.add(new Option(str, str));
    }
}

var myChart = echarts.init(document.getElementById('main'));

set_selection();

document.getElementById("submit").onclick = onSubmitClick;
